/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao.implementations;

import com.microsoft.sqlserver.jdbc.SQLServerException;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Handles SQL server connections and executes queries.
 * @author Johnny
 */
public abstract class DaoMsSql {

    protected static Connection con;
    protected SQLServerDataSource ds;

    public DaoMsSql() {
        // Setting up the connection properties
        ds = new SQLServerDataSource();
        ds.setServerName("127.0.0.1");
        ds.setUser("java");
        ds.setPassword("java");
        ds.setPortNumber(1433);
        ds.setDatabaseName("TransView");
    }

    /**
     * Creates the connection if it hasn't been created yet.
     * @return True if it was successful, false otherwise.
     */
    protected boolean createConnection() {
        try {
            con = ds.getConnection();
            return true;
        } catch (SQLServerException ex) {
            Logger.getLogger(DaoMsSql.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    /**
     * Closes the conenction.
     */
    protected void closeConnection() {
        try {
            if (con!=null)
                con.close();
        } catch (SQLException ex) {
            Logger.getLogger(DaoMsSql.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Renew the connection if it is invalid.
     */
    protected void checkConnection() {
        try {
            if (con == null || !con.isValid(2)) {
                createConnection();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DaoMsSql.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Gets a statement of the active connection.
     * @return The statement of the active connection.
     */
    protected Statement getStatement() {
        checkConnection();
        try {
            return con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        } catch (SQLException ex) {
            Logger.getLogger(DaoMsSql.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}
